import requests
import random
import os
import asyncio
import aiohttp
import aiofiles
import time


x = input('请输入你想爬取的图片类型：')
pg = int(input('请输入欲爬取的页数（一页包含30张）：'))

t1 = time.time()


def main():
    b = ['Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19','Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0\
             ','Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36','Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19','Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3','Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3']
    headers = {
        'User-Agent':random.choice(b)
    }
    return headers


headers = main()
pn = 29
n = 0
if os.path.exists('百度图片爬取'):
    pass
else:
    os.makedirs('百度图片爬取')


async def main():
    global pn
    global n
    for i in range(pg):
        url = 'https://image.baidu.com/search/acjson'
        param = {
                'tn': 'resultjson_com',
                'logid': '8846269338939606587',
                'ipn': 'rj',
                'ct': '201326592',
                'is': '',
                'fp': 'result',
                'queryWord': x,
                'cl': '2',
                'lm': '-1',
                'ie': 'utf-8',
                'oe': 'utf-8',
                'adpicid': '',
                'st': '-1',
                'z': '',
                'ic': '',
                'hd': '',
                'latest': '',
                'copyright': '',
                'word': x,
                's': '',
                'se': '',
                'tab': '',
                'width': '',
                'height': '',
                'face': '0',
                'istype': '2',
                'qc': '',
                'nc': '1',
                'fr': '',
                'expermode': '',
                'force': '',
                'cg': 'girl',
                'pn': pn,
                'rn': '30',
                'gsm': '1e',
            }
        response = requests.get(url=url, headers=headers, params=param)
        response = response.json()['data']
        del response[-1]
        tasks = []
        for i in response:
            filename = str(n) + '.jpg'
            tasks.append(download(i['thumbURL'],filename))
            n = n+1
        pn = pn+30
        await asyncio.wait(tasks)


async def download(url,name):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            async with aiofiles.open('百度图片爬取/' + name, 'wb') as f:
                await f.write(await resp.content.read())


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    t2 = time.time()
    print(t2-t1)